require 'open-uri'

def raw_dir(size)
  sprintf("raw/%s", size)
end

def raw_files(size)
  (5208..5280).collect {|n| sprintf("raw/%s/big_buck_bunny_%05d.png", size, n)}
end

# 640x360
directory raw_dir("640x360")

rule %r(raw/640x360/big_buck_bunny_[0-9]+\.png) => raw_dir("640x360") do |t|
  url = sprintf("http://media.xiph.org/BBB/BBB-360-png/%s", t.name.pathmap("%f"))
  puts "Grabbing #{url}"
  open(url) do |s|
    IO.copy_stream(s, t.name)
  end
end

file "test_640x360.h264" => raw_files("640x360") do |f|
  sh "ffmpeg -y -start_number 5208 -i raw/640x360/big_buck_bunny_%05d.png -pix_fmt yuv420p -c:v libx264 -x264-params keyint=40 -profile:v baseline -f rawvideo test_640x360.h264"
end

# 1920x1080
directory raw_dir("1920x1080")

rule %r(raw/1920x1080/big_buck_bunny_[0-9]+\.png) => raw_dir("1920x1080") do |t|
  url = sprintf("http://media.xiph.org/BBB/BBB-1080-png/%s", t.name.pathmap("%f"))
  puts "Grabbing #{url}"
  open(url) do |s|
    IO.copy_stream(s, t.name)
  end
end

file "test_1920x1080.h264" => raw_files("1920x1080") do |f|
  sh "ffmpeg -y -start_number 5208 -i raw/1920x1080/big_buck_bunny_%05d.png -pix_fmt yuv420p -c:v libx264 -x264-params keyint=40 -profile:v baseline -f rawvideo test_1920x1080.h264"
end

desc "Generate encoded test h264 files."
task :generate_test_data => ["test_640x360.h264", "test_1920x1080.h264"]


rule ".yuv" => ".h264" do |t|
  sh "ffmpeg -y -i #{t.source} -c:v rawvideo -pix_fmt yuv420p #{t.name}"
end

desc "Generate decoded yuv test data using ffmpeg. This data is used when comparing decoded output with a known-good sample."
task :generate_output_data => ["test_640x360.yuv", "test_1920x1080.yuv"]

task :clean do
  FileUtils.rm_rf "raw"
  FileUtils.rm_f "test_640x360.h264"
  FileUtils.rm_f "test_1920x1080.h264"
  FileUtils.rm_f "test_640x360.yuv"
  FileUtils.rm_f "test_1920x1080.yuv"
end

task :default => [:generate_test_data]
